package com.easy.system.database;

import com.easy.yours.biz.model.Clazz;
import com.easy.yours.biz.model.Student;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.cfg.Configuration;
import org.hibernate.tool.hbm2ddl.SchemaExport;
import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: sunguangzhu
 * Date: 13-7-30
 * Time: 下午9:06
 * To change this template use File | Settings | File Templates.
 */
public class HibernateUtils {
    public static void ExportDB() throws ClassNotFoundException {
       /* Configuration cfg = new Configuration().configure();
        SchemaExport export = new SchemaExport(cfg);
        export.create(true, true);*/
      /*  Configuration configuration = new AnnotationConfiguration();
        configuration.configure();
        SchemaExport export = new SchemaExport(configuration);
        export.execute(true, true, false, true);*/
        Configuration configuration = HibernateUtils.getCfg("com.easy.yours.biz.model");
        SchemaExport export = new SchemaExport(configuration);
        export.execute(true, true, false, true);
    }

    public static  Configuration getCfg (String packageName) throws ClassNotFoundException {
        AnnotationConfiguration configuration = new AnnotationConfiguration().configure().addPackage(packageName);
        List<String> classNames = HibernateUtils.getClassNames(packageName);
        for (String className : classNames) {
            Class clazz = Class.forName(className);
            configuration.addAnnotatedClass(clazz);
        }
        return configuration;
    }

    public static List<String> getClassNames(String packageName){
        String packagePath = packageName.replace(".","/");
        String dir = System.getProperty("user.dir");
        String path = dir + "/src/main/java/"+packagePath;
        File fileDir =new File(path);
        List<String> classNames = new ArrayList<String>();
        if(fileDir.isDirectory()){
            String[]  files = fileDir.list();
            for(String fileName : files){
                classNames.add(packageName+"."+fileName.replace(".java",""));
            }
        }
        return  classNames;
    }

    public static void main(String[] args) throws ClassNotFoundException {
        HibernateUtils.ExportDB();
//        System.out.println("System.getProperty(\"user.dir\") = " + System.getProperty("user.dir"));
//        System.out.println("\"com.easy.system.model\".replace(\".\",\"/\") = " + "com.easy.system.model".replace(".", "/"));

    }
}
